package com.sta.staff.controller.backstage;

import com.sta.staff.bean.Result;
import com.sta.staff.pojo.Message;
import com.sta.staff.pojo.Salary;
import com.sta.staff.pojo.Users;
import com.sta.staff.service.MessageService;
import com.sta.staff.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/backstage/message")
public class MessageController {
    @Autowired
    private MessageService messageService;
    @Autowired
    private UsersService usersService;
    //查询所有留言
    @RequestMapping("/all")
    public ModelAndView all(){
        ModelAndView modelAndView = new ModelAndView();
        List<Message> allMessage = messageService.find();

        modelAndView.addObject("allMessage",allMessage);
        modelAndView.setViewName("/backstage/message");
        return modelAndView;
    }

    //新增留言
    @RequestMapping("/add")
    public ModelAndView add(Message message){
        ModelAndView modelAndView = new ModelAndView();
        // 1.获取会话对象
        SecurityContext context = SecurityContextHolder.getContext();
        // 2.获取认证对象
        Authentication authentication = context.getAuthentication();
        // 3.获取登录用户信息
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String username = userDetails.getUsername();

        Users user = usersService.findByUsersName(username);
        Integer uid = user.getUid();
        messageService.add(uid,message);
        modelAndView.setViewName("redirect:/backstage/message/all");
        return modelAndView;
    }

    //删除员工留言
    @RequestMapping("/delete")
    public String delete(Integer mid){
        messageService.delete(mid);
        return "redirect:/backstage/message/all";
    }

}
